import os
import json
import logging
from typing import Any, Dict

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny

from utils.JWTTool import JwtUtils
from rest_framework.exceptions import AuthenticationFailed

from .agents.boss_agent import BossAgent

logger = logging.getLogger(__name__)


def clean_text(text: str) -> str:
    try:
        if not text:
            return ""
        # 与项目一致：移除emoji/特殊字符/HTML，保留中英文与基础标点
        import re
        emoji_pattern = re.compile("[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF\u2600-\u26FF\u2700-\u27BF\U0001F900-\U0001F9FF\U0001FA70-\U0001FAFF]+", flags=re.UNICODE)
        special_chars_pattern = re.compile(r"[^\w\s\u4e00-\u9fff\u3000-\u303f\uff00-\uffef.,!?;:()\[\]{}\"'`~@#$%^&*+=|\\/<>-]")
        t = emoji_pattern.sub('', text)
        t = special_chars_pattern.sub('', t)
        return t.strip()
    except Exception:
        return text or ""


def get_user_id_from_auth(request) -> int:
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    if not auth_header or not auth_header.startswith('Bearer '):
        raise AuthenticationFailed('未提供认证Token或格式错误')
    token = auth_header.split(' ')[1]
    if not token:
        raise AuthenticationFailed('Token不能为空')
    return JwtUtils.get_user_id_from_token(token)


@method_decorator(csrf_exempt, name='dispatch')
class BossAgentAPIView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        try:
            user_id = get_user_id_from_auth(request)
        except AuthenticationFailed as e:
            return Response({"code": 0, "message": f"认证失败:{e}"})

        # 添加调试信息
        logger.info(f"接收到的请求数据: {request.data}")
        logger.info(f"请求数据类型: {type(request.data)}")
        
        question = request.data.get('question') or ''
        session_id = request.data.get('session_id') or ''
        
        # 添加调试信息
        logger.info(f"提取的question: '{question}'")
        logger.info(f"question类型: {type(question)}")
        logger.info(f"question长度: {len(question) if question else 0}")
        
        if not question:
            logger.warning(f"问题为空，原始数据: {request.data}")
            return Response({"code": 0, "message": "问题不能为空"})

        agent = BossAgent()
        result = agent.run(clean_text(question), user_id=user_id, session_id=session_id)
        data = {"response": clean_text(result.get("response", "")), "user_id": user_id, "session_id": session_id}
        return Response({"code": 200, "message": "ok", "data": data})

from django.shortcuts import render


@method_decorator(csrf_exempt, name='dispatch')
class BossAgentDebugView(APIView):
    """调试视图，用于测试认证和获取系统状态"""
    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """调试GET请求"""
        return Response({
            "code": 200,
            "message": "Agent Boss 调试接口",
            "data": {
                "status": "running",
                "endpoints": [
                    "POST /agent_boss/chat/ - 主要聊天接口",
                    "GET /agent_boss/debug/ - 调试接口",
                ],
                "tools": [
                    "ResumeGenerateOrAnalyze - 简历生成/分析",
                    "JobSearch - 职位搜索",
                    "KnowledgeSearch - 知识检索"
                ]
            }
        })

    def post(self, request):
        """调试POST请求"""
        debug_info = {
            "request_data": request.data,
            "auth_header": request.META.get('HTTP_AUTHORIZATION', ''),
            "all_headers": {k: v for k, v in request.META.items() if k.startswith('HTTP_')},
            "method": request.method,
            "path": request.path,
        }
        
        logger.info(f"调试信息: {debug_info}")
        
        return Response({
            "code": 200, 
            "message": "调试信息", 
            "data": debug_info
        })


# Create your views here.
